<template>
    <div class="header">
        <!--展开和收缩的图标-->
        <div style="font-size: 20px">
            <i class="el-icon-s-unfold" v-if="!isShow" @click="changeIsShow"></i>
            <i class="el-icon-s-fold" v-if="isShow" @click="changeIsShow"></i>
        </div>
        <!--用户信息展示-->
        <div>
            <el-header style="text-align: right; font-size: 14px;margin-top: 5px">
                <span>{{nickName}}</span>
                <el-dropdown>
                    <i class="el-icon-setting" style="margin-left: 15px"></i>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="editUserInfo">个人资料</el-dropdown-item>
                        <el-dropdown-item @click.native="showEditPassword">修改密码</el-dropdown-item>
                        <el-dropdown-item @click.native="logout">安全退出</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-header>
        </div>
        <!--个人信息弹出层  :visible.sync 控制弹出层显示还是隐藏 true 显示  false隐藏-->
        <el-dialog title="个人信息" :visible.sync="userFormVisible" width="40%" @close="cleanValidate">
            <el-form :model="userForm" ref="userFormRef" :rules="userFormRules" label-width="80px" label-position="left">
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="userForm.nickName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="userForm.sex" placeholder="请选择性别" style="width: 100%">
                        <el-option label="男" :value="1"></el-option>
                        <el-option label="女" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="userForm.city" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input v-model="userForm.tel" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="userFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </div>
        </el-dialog>

        <!--修改密码弹出层  :visible.sync 控制弹出层显示还是隐藏 true 显示  false隐藏-->
        <el-dialog title="修改密码" :visible.sync="passwordFormVisible" width="40%" @close="clearPasswordInfo">
            <el-form :model="passwordForm" ref="passwordFormRef" label-width="80px" :rules="editPasswordFormRules"
                     label-position="top">
                <el-form-item label="请输入旧密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请输入新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请确认密码" prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="passwordFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editPassword">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getPersonalInfoApi, updatePersonalInfoApi, editUserPasswordApi} from '@/request/api'

    export default {
        name: "HeaderView",
        data() {
            // 自定义校验规则
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passwordForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                isShow: true,
                userFormVisible: false,
                passwordFormVisible: false,
                nickName: window.sessionStorage.getItem("nickName"),
                userForm: {},
                userFormRules:{
                    nickName: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                    ]
                },
                passwordForm: {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                },
                editPasswordFormRules: {  // 修改密码表单验证规则对象
                    oldPassword: [
                        {required: true, message: '请输入原始密码', trigger: 'blur'},
                    ],
                    newPassword: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur'}
                    ],
                    confirmPassword: [
                        {validator: validatePass2, trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            changeIsShow() {
                this.isShow = !this.isShow
                // 调用 vuex中的mutations提供的修改 IsCollapse值的 changeIsCollapse 函数
                this.$store.commit('changeIsCollapse')
                // 改变navbar的宽度  changeCollapseClass
                this.$store.commit('changeCollapseClass')
            },
            // 编辑个人信息
            editUserInfo() {
                // 发送异步请求 获取当前用户信息
                getPersonalInfoApi().then(response => {
                    this.userForm = response.data
                }).catch(error => {
                    this.$message.error("请求失败")
                })
                this.userFormVisible = true
            },
            // 修改密码
            showEditPassword() {
                this.passwordFormVisible = true
            },
            editPassword() {
                this.$refs.passwordFormRef.validate(valid => {
                    if (!valid) {
                        this.$message.warning("请填写完整的密码信息！！")
                        return
                    }
                    // 发送异步请求 实现用户密码的修改
                    editUserPasswordApi(this.passwordForm).then(response => {
                        if (response.code == 200) {
                            this.$message({
                                type: 'success',
                                message: response.msg,
                                onClose: () => {
                                    this.passwordFormVisible = false
                                    this.passwordForm = {
                                        oldPassword: '',
                                        newPassword: '',
                                        confirmPassword: ''
                                    }
                                    window.sessionStorage.removeItem("token")
                                    window.sessionStorage.removeItem("nickName")
                                    this.$router.push("/login")
                                }
                            })
                            return
                        }
                        this.$message.error(response.msg)
                    }).catch(error => {
                        this.$message.error("请求失败")
                    })

                })
            },
            // 退出登录
            logout() {
                // 弹出确认提示
                this.$confirm('请确认是否退出登录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '退出登录成功!',
                        onClose: () => {
                            // 清除token    nickName
                            window.sessionStorage.removeItem("token")
                            window.sessionStorage.removeItem("nickName")
                            // 清空菜单数据
                            this.$store.commit("changeMenuData",[])
                            this.$router.push("/login")
                        }
                    });

                }).catch(() => {
                    this.$message({type: 'info', message: '取消退出'});
                });
            },
            //清空弹窗信息
            clearPasswordInfo() {
                this.passwordForm = {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                }
                // 重置表单参数  解决重新打开提示验证错误信息问题
                this.$refs.passwordFormRef.clearValidate()
            },
            // 编辑个人资料
            editUser() {
                this.$refs.userFormRef.validate(valid=>{
                    if(!valid){
                        this.$message.warning("请填写必要数据")
                        return
                    }
                    // 发送异步请求 编辑个人资料
                    let {id, nickName, sex, tel, city} = this.userForm
                    updatePersonalInfoApi({id, nickName, sex, tel, city}).then(response => {
                        // 编辑成功 关闭弹窗
                        if (response.code == 200) {
                            window.sessionStorage.setItem("nickName", nickName)
                            this.$message.success(response.msg);
                            this.userFormVisible = false;
                            window.location.reload();
                            return
                        }
                        this.$message.error(response.msg)
                    }).catch(error => {
                        this.$message.error("请求失败")
                    })

                })
            },
            // 弹窗关闭 清除校验规则
            cleanValidate(){
                this.$refs.userFormRef.clearValidate();
            }
        }
    }
</script>

<style scoped>
    .header {
        display: flex;
        justify-content: space-between;
        height: 60px;
        padding-left: 20px;
        padding-top: 10px;
        box-sizing: border-box;
        box-shadow: 0px 5px 5px #ddd;
    }

    .el-icon-setting, .el-icon-s-fold, .el-icon-s-unfold {
        cursor: pointer;
    }
</style>
